{% extends "base.html" %}

{% block title %}简易房间预订 - 风之宿{% endblock %}

{% block content %}
<div class="container mx-auto px-4 py-8">
  <h1 class="text-3xl font-bold text-primary mb-2">简易房间预订</h1>
  <p class="text-gray-600 mb-8">选择理想房间，开启舒适旅程</p>

  <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
    <!-- 房间列表 -->
    <div class="bg-white rounded-xl shadow-md overflow-hidden">
      <div class="p-6 border-b border-gray-100">
        <h2 class="text-2xl font-semibold text-gray-800">可选房间</h2>
        <p class="text-gray-500 mt-1">选择适合您的理想房型</p>
      </div>

      <div class="divide-y divide-gray-100">
        {% for room in rooms %}
        <div class="p-6 hover:bg-gray-50 transition-colors room-item"
             data-room-id="{{ room.id }}"
             data-room-name="{{ room.name }}"
             data-room-price="{{ room.price }}">
          <div class="flex flex-col md:flex-row gap-6">
            <!-- 房间图片 -->
            <div class="md:w-1/3">
              <div class="rounded-lg overflow-hidden h-40 bg-gray-100 relative">
                <!-- 房间状态标签 -->
                <div class="absolute top-3 left-3 z-10">
                  {% if room.status == 'available' %}
                    <span class="px-2 py-1 bg-green-500 text-white text-xs rounded-md shadow-sm">
                      可预订
                    </span>
                  {% elif room.status == 'booked' %}
                    <span class="px-2 py-1 bg-red-500 text-white text-xs rounded-md shadow-sm">
                      已预订
                    </span>
                  {% elif room.status == 'maintenance' %}
                    <span class="px-2 py-1 bg-yellow-500 text-white text-xs rounded-md shadow-sm">
                      维护中
                    </span>
                  {% endif %}
                </div>

                {% if room.image_url %}
                  <img src="{{ url_for('static', filename='uploads/' + room.image_url) }}"
                       alt="{{ room.name }}"
                       class="w-full h-full object-cover">
                {% else %}
                  <img src="{{ url_for('static', filename='images/default-room.png') }}"
                       alt="默认房间图片"
                       class="w-full h-full object-cover">
                {% endif %}
              </div>
            </div>

            <!-- 房间信息 -->
            <div class="md:w-2/3">
              <div class="flex flex-col md:flex-row md:justify-between gap-2">
                <div>
                  <h3 class="text-xl font-semibold text-gray-800">{{ room.name }}</h3>
                  <div class="flex items-center mt-1">
                    <span class="text-sm text-gray-500 mr-3">容纳 {{ room.capacity }} 人</span>
                    <span class="text-sm px-2 py-0.5 bg-gray-100 text-gray-600 rounded">
                      {{ room.room_type }}
                    </span>
                  </div>
                </div>
                <div class="text-right">
                  <span class="text-primary font-bold text-xl">¥{{ room.price }}</span>
                  <span class="text-gray-500 text-sm">/晚</span>
                </div>
              </div>

              <p class="text-gray-600 mt-3 text-sm">{{ room.description }}</p>

              <!-- 选择按钮 -->
              <div class="mt-4">
                <button type="button"
                        class="select-room-btn px-4 py-2 border border-primary text-primary rounded-md hover:bg-primary hover:text-white transition-colors text-sm font-medium {% if room.status != 'available' %}opacity-50 cursor-not-allowed{% endif %}"
                        data-room-id="{{ room.id }}"
                        data-room-name="{{ room.name }}"
                        data-room-price="{{ room.price }}"
                        {% if room.status != 'available' %}disabled{% endif %}>
                  {% if room.status == 'available' %}选择此房间{% else %}不可预订{% endif %}
                </button>
              </div>
            </div>
          </div>
        </div>
        {% endfor %}
      </div>
    </div>

    <!-- 预订表单 -->
    <div class="lg:col-span-1">
      <div class="sticky top-6">
        <div class="bg-white rounded-xl shadow-md p-6">
          <h2 class="text-xl font-semibold text-gray-800 mb-5">预订信息</h2>

          <form id="booking-form" class="space-y-5">
            <div>
              <label for="room_id" class="block text-sm font-medium text-gray-700 mb-1">已选房间</label>
              <div class="relative">
                <input type="text" id="selected_room_display" readonly
                       class="w-full px-3 py-2 border border-gray-300 rounded-md bg-gray-50 text-gray-900"
                       placeholder="请从左侧选择房间">
                <input type="hidden" id="room_id" name="room_id" required>
              </div>
            </div>

            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <label for="check_in" class="block text-sm font-medium text-gray-700 mb-1">入住日期</label>
                <input type="date" id="check_in" name="check_in" required
                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-primary focus:border-primary">
              </div>

              <div>
                <label for="check_out" class="block text-sm font-medium text-gray-700 mb-1">退房日期</label>
                <input type="date" id="check_out" name="check_out" required
                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-primary focus:border-primary">
              </div>
            </div>

            <div>
              <label for="guests" class="block text-sm font-medium text-gray-700 mb-1">入住人数</label>
              <input type="number" id="guests" name="guests" min="1" max="10" required
                     class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-primary focus:border-primary"
                     placeholder="入住人数">
            </div>

            <!-- 预订信息预览 -->
            <div class="bg-gray-50 p-4 rounded-lg">
              <h3 class="font-medium text-gray-800 mb-3">预订详情</h3>
              <div class="space-y-2 text-sm">
                <div class="flex justify-between">
                  <span class="text-gray-600">房间价格:</span>
                  <span id="price_display" class="text-gray-800">¥0/晚</span>
                </div>
                <div class="flex justify-between">
                  <span class="text-gray-600">入住天数:</span>
                  <span id="days_display" class="text-gray-800">0天</span>
                </div>
                <div class="border-t border-gray-200 my-2 pt-2 flex justify-between font-medium">
                  <span class="text-gray-700">总计:</span>
                  <span id="total_display" class="text-primary">¥0</span>
                </div>
              </div>
            </div>

            <button type="submit" id="book-button" class="w-full bg-primary text-white py-3 px-4 rounded-md hover:bg-primary/90 transition-colors font-semibold shadow-sm hover:shadow disabled:opacity-50 disabled:cursor-not-allowed">
              确认预订
            </button>
          </form>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
  // 获取DOM元素
  const checkInInput = document.getElementById('check_in');
  const checkOutInput = document.getElementById('check_out');
  const roomIdInput = document.getElementById('room_id');
  const selectedRoomDisplay = document.getElementById('selected_room_display');
  const priceDisplay = document.getElementById('price_display');
  const daysDisplay = document.getElementById('days_display');
  const totalDisplay = document.getElementById('total_display');
  const selectRoomBtns = document.querySelectorAll('.select-room-btn');
  const bookingForm = document.getElementById('booking-form');
  const bookButton = document.getElementById('book-button');

  // 存储当前选择的房间价格
  let currentRoomPrice = 0;
  let currentRoomId = null;

  // 设置最小日期为今天
  const today = new Date().toISOString().split('T')[0];
  checkInInput.min = today;
  checkOutInput.min = today;

  // 默认设置入住日期为今天，退房日期为明天
  checkInInput.value = today;
  const tomorrow = new Date();
  tomorrow.setDate(tomorrow.getDate() + 1);
  checkOutInput.value = tomorrow.toISOString().split('T')[0];

  // 当入住日期改变时，更新退房日期的最小值
  checkInInput.addEventListener('change', function() {
    checkOutInput.min = this.value;
    // 如果退房日期早于入住日期，自动调整
    if (checkOutInput.value && checkOutInput.value < this.value) {
      checkOutInput.value = this.value;
    }
    calculateTotal();
  });

  // 当退房日期改变时，更新总价
  checkOutInput.addEventListener('change', function() {
    calculateTotal();
  });

  // 房间选择按钮点击事件
  selectRoomBtns.forEach(btn => {
    btn.addEventListener('click', function() {
      if (this.disabled) return;

      const roomId = this.getAttribute('data-room-id');
      const roomName = this.getAttribute('data-room-name');
      const roomPrice = this.getAttribute('data-room-price');

      // 更新表单值
      currentRoomId = roomId;
      roomIdInput.value = roomId;
      selectedRoomDisplay.value = roomName;
      currentRoomPrice = parseFloat(roomPrice);

      // 更新显示价格
      priceDisplay.textContent = `¥${currentRoomPrice}/晚`;

      // 重新计算总价
      calculateTotal();

      // 高亮显示选中的房间
      document.querySelectorAll('.room-item').forEach(roomEl => {
        roomEl.classList.remove('ring-2', 'ring-primary', 'ring-opacity-50');
      });
      this.closest('.room-item').classList.add('ring-2', 'ring-primary', 'ring-opacity-50');
    });
  });

  // 计算入住天数和总价
  function calculateTotal() {
    if (!checkInInput.value || !checkOutInput.value || currentRoomPrice <= 0) {
      return;
    }

    const checkIn = new Date(checkInInput.value);
    const checkOut = new Date(checkOutInput.value);

    // 计算天数差
    const timeDiff = checkOut - checkIn;
    const dayDiff = Math.ceil(timeDiff / (1000 * 3600 * 24));

    // 确保天数不为负
    const days = Math.max(dayDiff, 1);
    const total = currentRoomPrice * days;

    // 更新显示
    daysDisplay.textContent = `${days}天`;
    totalDisplay.textContent = `¥${total.toFixed(2)}`;
  }

  // 表单提交事件
  bookingForm.addEventListener('submit', function(e) {
    e.preventDefault();
    
    // 检查必要条件
    if (!currentRoomId || !checkInInput.value || !checkOutInput.value || !document.getElementById('guests').value) {
      alert('请填写完整的预订信息');
      return;
    }
    
    // 禁用提交按钮防止重复提交
    bookButton.disabled = true;
    bookButton.textContent = '预订中...';
    
    // 准备预订数据
    const bookingData = {
      room_id: currentRoomId,
      check_in: checkInInput.value,
      check_out: checkOutInput.value,
      guests: document.getElementById('guests').value
    };
    
    // 发送预订请求
    fetch('/api/simple_bookings/create', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(bookingData)
    })
    .then(response => response.json())
    .then(data => {
      if (data.success) {
        alert('预订成功！');
        // 重置表单
        bookingForm.reset();
        selectedRoomDisplay.value = '';
        priceDisplay.textContent = '¥0/晚';
        daysDisplay.textContent = '0天';
        totalDisplay.textContent = '¥0';
        currentRoomId = null;
        currentRoomPrice = 0;
        
        // 移除房间高亮
        document.querySelectorAll('.room-item').forEach(roomEl => {
          roomEl.classList.remove('ring-2', 'ring-primary', 'ring-opacity-50');
        });
      } else {
        alert('预订失败: ' + data.message);
      }
    })
    .catch(error => {
      console.error('预订请求失败:', error);
      alert('预订请求失败，请稍后重试');
    })
    .finally(() => {
      // 恢复提交按钮
      bookButton.disabled = false;
      bookButton.textContent = '确认预订';
    });
  });

  // 初始化计算
  calculateTotal();
});
</script>
{% endblock %}